<template>
  <div class="create-post-container">
    <el-form ref="postForm" :model="postForm" label-position="top" label-width="100px" class="user-form">
      <el-row :gutter="20">
        <el-col :span="9" :offset="3">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="postForm.name" />
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="是否为内部用户" prop="isinterior" class="text-center">
            <el-switch v-model="postForm.isinterior" :active-value="1" :inactive-value="0" />
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="是否为VIP" prop="level" class="text-center">
            <el-switch v-model="isVip" :active-value="1" :inactive-value="0" @change="changeLevel" />
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="是否为Global" prop="isGlobal" class="text-center">
            <el-switch v-model="postForm.isGlobal" :active-value="1" :inactive-value="0" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item v-if="showVeevaGroup" label="VeevaId 和 VeevaCode" prop="veevagroup">
            <el-row
              v-for="(item, index) in postForm.veevagroup"
              :key="index"
              :gutter="20"
              class="veeva-row"
            >
              <el-col :span="12">
                <el-form-item>
                  <el-input v-model="item.veeva_id" type="number" placeholder="请输入 VeevaId">
                    <template slot="prepend">VeevaId</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item>
                  <el-input v-model="item.veeva_code" placeholder="请输入 VeevaCode">
                    <template slot="prepend">VeevaCode</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="1">
                <el-button
                  v-if="index === 0"
                  type="text"
                  icon="el-icon-plus"
                  style="width: 100%;"
                  @click="addVeeva"
                />
                <el-button
                  v-else
                  type="text"
                  icon="el-icon-delete"
                  style="width: 100%;"
                  @click="removeVeeva(index, item)"
                />
              </el-col>
            </el-row>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="9" :offset="3">
          <el-form-item label="Mrid" prop="mrid">
            <el-input v-model="postForm.mrid" />
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="MrUserId" prop="mruserId">
            <el-input v-model="postForm.mruserId" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="9" :offset="3">
          <el-form-item label="手机号码" prop="tel">
            <el-input v-model="postForm.tel" type="tel" />
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="postForm.email" type="email" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="9" :offset="3">
          <el-form-item label="状态" prop="state">
            <el-select
              v-model="postForm.state"
              placeholder="请选择"
              style="width:100%"
            >
              <el-option
                v-for="item in stateOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="用户类型" prop="type">
            <el-select
              v-model="postForm.type"
              placeholder="请选择"
              style="width:100%"
            >
              <el-option
                v-for="item in typeOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="9" :offset="3">
          <el-form-item label="当前注册信息来源" prop="source">
            <el-select
              v-model="postForm.source"
              placeholder="请选择"
              style="width:100%"
            >
              <el-option
                v-for="item in sourceOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="所属群组" prop="cluster">
            <el-select
              v-model="postForm.cluster"
              placeholder="请选择"
              style="width:100%"
            >
              <el-option
                v-for="item in clusterOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="9" :offset="3">
          <el-form-item label="省份" prop="provinceCode">
            <el-select
              v-model="postForm.provinceCode"
              filterable
              clearable
              placeholder="请选择"
              style="width:100%"
              @change="changeProvince"
            >
              <el-option
                v-for="item in provinceOptions"
                :key="item.id"
                :label="item.province_name"
                :value="item.province_code"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="城市" prop="cityCode">
            <el-select
              v-model="postForm.cityCode"
              filterable
              clearable
              placeholder="请选择"
              style="width:100%"
              @change="changeCity"
            >
              <el-option
                v-for="item in cityOptions"
                :key="item.id"
                :label="item.city_name"
                :value="item.city_code"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="!isNoCity ? 6 : 9" :offset="3">
          <el-form-item label="医院名称" prop="hospname">
            <el-input v-model="postForm.hospname" disabled />
            <div class="form-tips text-warning">如需修改医院，请先筛选省份和城市。</div>
          </el-form-item>
        </el-col>
        <el-col v-if="!isNoCity" :span="6">
          <el-form-item label="医院" prop="hospid">
            <el-select
              v-model="postForm.hospid"
              filterable
              clearable
              placeholder="请选择"
              style="width:100%"
            >
              <el-option
                v-for="item in hospitalOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="!isNoCity ? 6 : 9">
          <el-form-item label="科室" prop="deparrment">
            <el-select
              v-model="postForm.deparrment"
              filterable
              clearable
              placeholder="请选择"
              style="width:100%"
            >
              <el-option
                v-for="item in deparpmentOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="6" :offset="3">
          <el-form-item label="QrCodeId" prop="qrCodeId">
            <el-input v-model="postForm.qrCodeId" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="注册时间" prop="registerTime">
            <el-date-picker
              v-model="postForm.registerTime"
              type="datetime"
              placeholder="选择注册时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              style="width:100%"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="同意协议时间" prop="ruleTime">
            <el-date-picker
              v-model="postForm.ruleTime"
              type="datetime"
              placeholder="选择同意协议时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              style="width:100%"
              disabled
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="9" :offset="3">
          <el-form-item label="绑定产品" prop="brandId">
            <el-select
              v-model="postForm.brandId"
              filterable
              clearable
              placeholder="请选择"
              style="width:100%"
            >
              <el-option
                v-for="item in productsOptions"
                :key="item.id"
                :label="item.brand"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="9">
          <el-form-item label="标签" prop="lable">
            <el-select
              v-model="postForm.lable"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="可自行输入，并按下回车选择标签"
              style="width:100%"
            >
              <el-option
                v-for="(item, index) in postForm.lable"
                :key="index"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="备注" prop="notes">
            <el-input v-model="postForm.notes" type="textarea" rows="4" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="mt30">
        <el-col :span="18" :offset="3">
          <el-form-item>
            <el-button type="primary" @click="submitForm">保 存</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import {
  getUsersList,
  editUser
} from '@/api/users'
import {
  getProvince,
  getCities,
  getDepartments,
  getHospitalsByCity,
  getUserState,
  getUserType,
  getUserSource,
  getAllCluster,
  getProducts
} from '@/api/baseData'

const defaultForm = {
  id: undefined,
  name: '',
  isinterior: 0,
  level: '',
  isGlobal: 0,
  veevagroup: [
    {
      veeva_id: '',
      veeva_code: ''
    }
  ],
  mrid: '',
  mruserId: '',
  tel: '',
  email: '',
  state: '',
  type: '',
  province: '',
  provinceCode: '',
  city: '',
  cityCode: '',
  hospid: '',
  hospname: '',
  deparrment: '',
  source: '',
  cluster: '',
  lable: [],
  notes: '',
  qrCodeId: '',
  registerTime: '',
  ruleTime: '',
  brandId: ''
}

export default {
  name: 'UserForm',
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      provinceOptions: [],
      cityOptions: [],
      hospitalOptions: [],
      deparpmentOptions: [],
      stateOptions: [],
      typeOptions: [],
      sourceOptions: [],
      clusterOptions: [],
      productsOptions: [],
      isVip: 0,
      showVeevaGroup: true,
      postForm: Object.assign({}, defaultForm),
      loading: false
      // rules: {
      //   name: [
      //     { required: true, message: '请输入姓名', trigger: 'blur' },
      //     { min: 1, max: 50, message: '长度在 1 到 50 个字', trigger: 'blur' }
      //   ],
      //   tel: [
      //     { required: true, message: '请输入手机号码', trigger: 'blur' }
      //   ],
      //   email: [
      //     { required: true, message: '请输入邮箱', trigger: 'blur' },
      //     { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
      //   ],
      //   state: [
      //     { required: true, message: '请选择状态', trigger: 'change' }
      //   ],
      //   type: [
      //     { required: true, message: '请选择状态', trigger: 'change' }
      //   ],
      //   hospid: [
      //     { required: true, message: '请选择所属医院', trigger: 'change' }
      //   ],
      //   deparrment: [
      //     { required: true, message: '请选择所属科室', trigger: 'change' }
      //   ],
      //   source: [
      //     { required: true, message: '请选择当前注册信息来源', trigger: 'change' }
      //   ],
      //   cluster: [
      //     { required: true, message: '请选择所属群组', trigger: 'change' }
      //   ]
      // }
    }
  },
  computed: {
    isNoCity() {
      return this._.isEmpty(this.postForm.provinceCode) || this._.isEmpty(this.postForm.cityCode)
    }
  },
  created() {
    this.fetchProvince()
    // this.fetchHospitals()
    this.fetchDepartments()
    this.fetchUserState()
    this.fetchUserType()
    this.fetchUserSource()
    this.fetchClusterList()
    this.fetchtProductsList()
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      this.fetchData(id)
    }
  },
  methods: {
    fetchProvince() {
      getProvince().then(response => {
        // console.log(response)
        this.provinceOptions = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    fetchCities(code) {
      getCities({ provinceCode: code }).then(response => {
        // console.log(response)
        this.cityOptions = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    fetchHospitals() {
      getHospitalsByCity({
        provinceCode: this.postForm.provinceCode,
        cityCode: this.postForm.cityCode
      }).then(response => {
        // console.log(response)
        this.hospitalOptions = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    fetchDepartments() {
      getDepartments().then(response => {
        // console.log(response)
        this.deparpmentOptions = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    fetchUserState() {
      getUserState().then(response => {
        // console.log(response)
        this.stateOptions = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    fetchUserType() {
      getUserType().then(response => {
        // console.log(response)
        this.typeOptions = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    fetchUserSource() {
      getUserSource().then(response => {
        // console.log(response)
        this.sourceOptions = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    fetchClusterList() {
      getAllCluster().then(response => {
        // console.log(response)
        this.clusterOptions = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    fetchtProductsList() {
      getProducts().then(response => {
        // console.log(response)
        this.productsOptions = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    fetchData(id) {
      getUsersList({ id }).then(response => {
        const resData = response.data[0]
        // console.log(resData)
        this.postForm.lable = []
        resData.label.forEach((el, index) => {
          this.postForm.lable.push(el.labelid)
        })
        this.postForm.id = resData.id
        this.postForm.name = resData.name
        this.postForm.isinterior = resData.isinterior
        this.postForm.level = resData.level
        this.isVip = resData.level === 'vip' ? 1 : 0
        this.postForm.isGlobal = resData.isGlobal
        this.postForm.veevagroup = resData.veevaList
        this.postForm.mrid = resData.mrid
        this.postForm.mruserId = resData.mrUserId
        this.postForm.tel = resData.tel
        this.postForm.email = resData.email
        this.postForm.state = resData.state
        this.postForm.type = resData.type
        this.postForm.province = resData.province
        this.postForm.provinceCode = resData.provinceCode
        this.postForm.city = resData.city
        this.postForm.cityCode = resData.cityCode
        this.postForm.hospid = resData.hospid
        this.postForm.hospname = resData.hospname
        this.postForm.deparrment = resData.deparrment
        this.postForm.source = resData.source
        this.postForm.cluster = resData.cluster
        this.postForm.notes = resData.notes
        this.postForm.qrCodeId = resData.qrCodeId
        this.postForm.registerTime = resData.registerTime
        this.postForm.ruleTime = resData.ruleTime
        this.postForm.brandId = resData.brandId
        if (!this._.isEmpty(resData.provinceCode)) {
          this.fetchCities(resData.provinceCode)
          if (!this._.isEmpty(resData.cityCode)) {
            this.fetchHospitals()
          }
        }
      }).catch(err => {
        console.log(err)
      })
    },
    changeProvince(province) {
      this.postForm.city = ''
      this.postForm.cityCode = ''
      this.cityOptions = []
      this.postForm.hospid = ''
      this.hospitalOptions = []
      if (this._.isEmpty(province)) {
        this.postForm.province = ''
      } else {
        let provinceObj = {}
        provinceObj = this.provinceOptions.find((item) => {
          return item.province_code === province
        })
        this.postForm.province = provinceObj.province_name
        this.fetchCities(province)
      }
    },
    changeCity(city) {
      this.postForm.hospid = ''
      this.hospitalOptions = []
      if (this._.isEmpty(city)) {
        this.postForm.city = ''
      } else {
        let cityObj = {}
        cityObj = this.cityOptions.find((item) => {
          return item.city_code === city
        })
        this.postForm.city = cityObj.city_name
        this.fetchHospitals()
      }
    },
    changeLevel(val) {
      this.postForm.level = val === 1 ? 'vip' : ''
    },
    addVeeva() {
      this.postForm.veevagroup.push({
        veeva_id: '',
        veeva_code: ''
      })
    },
    removeVeeva(index, item) {
      this.$confirm('确认删除此项?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const idx = this.postForm.veevagroup.indexOf(item)
        if (idx !== -1) {
          this.postForm.veevagroup.splice(idx, 1)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    submitForm() {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.postForm.lable = this.postForm.lable.join(',')
          this.postForm.veevagroup = JSON.stringify(this.postForm.veevagroup)
          this.showVeevaGroup = false

          this.loading = true
          if (this.isEdit) {
            editUser(this.postForm).then(response => {
              // console.log(response)
              this.$notify({
                title: '成功',
                message: '编辑用户成功',
                type: 'success',
                duration: 2000
              })
              this.loading = false
              this.$router.go(-1)
            }).catch(err => {
              console.log(err)
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm() {
      this.$refs.postForm.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.create-post-container {
  position: relative;
  .user-form {
    padding: 40px;
  }
  .veeva-row + .veeva-row {
    margin-top: 10px;
  }
}
</style>
